package com.ubi.core.log;

import com.ubi.core.framework.exception.BaseBusinessException;
import com.ubi.core.framework.request.RequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class LogExceptionHandler extends AbstractHandlerExceptionResolver {

    private final Logger logger = LoggerFactory.getLogger(LogExceptionHandler.class);

    public LogExceptionHandler() {
        // if not set order highest,the exception will handle by the global
        // exception handler
        setOrder(HIGHEST_PRECEDENCE);
    }

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {
        if (!shouldLogException(ex)) {
            return null;
        }

        logRequest(request);
        logger.error("exception trace", ex);
        return null;
    }

    private void logRequest(HttpServletRequest request) {
        // log the request info
        logger.info("requestURL={}", request.getRequestURL());
        logger.info("serverPort={}", request.getServerPort());
        logger.info("contextPath={}", request.getContextPath());
        logger.info("requestMethod={}", request.getMethod());

        logHeaders(request);
        logParameters(request);
        logRequestBody(request);
    }

    private void logRequestBody(HttpServletRequest request) {
        // when upload file,the request will be converted to
        // DefaultMultipartHttpServletRequest
        if (!(request instanceof RequestWrapper)) {
            return;
        }
        String requestBody = ((RequestWrapper) request).getRequestBody();
        if (StringUtils.isNotEmpty(requestBody)) {
            logger.info("requestBody={}", requestBody);
        }
    }

    private void logParameters(HttpServletRequest request) {
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            logger.info("[param] {}={}", paramName, request.getParameter(paramName));
        }
    }

    private void logHeaders(HttpServletRequest request) {
        Enumeration headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String headerName = (String) headers.nextElement();
            logger.info("[header] {}={}", headerName, request.getHeader(headerName));
        }
    }

    private boolean shouldLogException(Exception exception) {
        return !(exception instanceof BaseBusinessException);
    }

}
